import fs from 'fs';

const showRun = (lang, attrs, runtimeConf) => {
  const hide = attrs?.some?.(item => {
    if (item[0] === 'hide' && item[1] === 'true') return true
  })
  return runtimeConf[lang] && !hide
}

// 创建打印代码块的插件
const runCodeBlockPlugin = (md, runtimeConf) => {
  // 保存原始的fence渲染器
  const defaultFence = md.renderer.rules.fence;

  // 重写fence渲染器以添加打印按钮
  md.renderer.rules.fence = (...args) => {
    const [tokens, idx, _options, env] = args;
    const token = tokens[idx];
    let code = token.content;
    const info = token.info.trim();

    const lang = (info.match(/^[a-zA-Z0-9]+/)?.[0] || "").toLowerCase(); // 获取语言并转为小写
    // 使用原始渲染器渲染代码块
    const rawCode = defaultFence(...args);

    if (lang === 'mermaid') {
      // 将 mermaid 代码转换为 base64 编码
      const base64Code = Buffer.from(code).toString('base64');

      // 构建 mermaid.ink SVG URL
      const mermaidInkUrl = `https://mermaid.ink/svg/${base64Code}`;

      const style = token.attrs?.map?.(item => item.join(':'))?.join(';')

      // 返回 object 标签，以 SVG 格式嵌入
      return `
        <div class="mermaid-container" >
          <object style="${style}" type="image/svg+xml" data="${mermaidInkUrl}" class="mermaid-svg">
            Mermaid diagram
          </object>
        </div>
      `;
    }

    // console.log("%c Line:34 🎂 token", "color:#7f2b82", token);
    if (!showRun(lang, token.attrs, runtimeConf)) {
      return rawCode
    }

    // console.log("%c Line:45 🥤 token", "color:#33a5ff", token);
    if (token?.src?.[0]) {
      code = fs.readFileSync(token?.src?.[0], 'utf-8');
    }

    // 获取文件路径
    const filePath = env.path || '未知文件';

    // 创建唯一ID
    const id = `code-block-${idx}`;
    const filePathId = `file-path-${idx}`;

    return `
      <div class="code-block-wrapper" >
        ${rawCode}
        <div  class="print-button">
        <button onclick="runBeforeCode('${id}', '${filePathId}','${lang}')">RunBefore</button>
        <button onclick="runCode('${id}', '${filePathId}','${lang}')">Run</button>
        </div>
        <textarea data-idx="${idx}" data-lang="${lang}" id="${id}" style="display: none;">${code}</textarea>
        <textarea id="${filePathId}" style="display: none;">${filePath}</textarea>
      </div>
    `;
  };
};

// 导出插件
export { runCodeBlockPlugin };
